//
//  UIViewControllerExtension.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import SnapKit
import Kingfisher
import SwiftyUserDefaults

// MARK: - 刷新
extension UIViewController {
    func wn_refreshHeader(completion: @escaping ReturnClosure) -> MJRefreshGifHeader {
        let header = MJRefreshGifHeader {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                completion()
            })
        }
        let arr = WNAnimation.wn_refLoadingArray
        header.setImages(arr, duration: TimeInterval(arr.count)/25, for: .refreshing)
        header.stateLabel?.isHidden = true
        header.lastUpdatedTimeLabel?.isHidden = true
        header.setTitle("下拉刷新", for: .idle)
        return header
    }
    
    func wn_refreshFooter(completion: @escaping ReturnClosure) -> MJRefreshAutoNormalFooter {
        let footer = MJRefreshAutoNormalFooter {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                completion()
            })
        }
        footer.stateLabel?.textColor = .init(named: "gray_CECECE")
        footer.stateLabel?.font = .wn_font(name: .bold, size: 11)
        footer.setTitle("", for: .idle)
        footer.setTitle("沒有更多", for: .noMoreData)
        return footer
    }
}

//MARK: - 计算文字宽高度
extension UIViewController {
    /// 计算文字高度
    func wn_getTextHeigh(textStr: String, font: UIFont, width: CGFloat, lineSpace: CGFloat, kernSpace: CGFloat = 0) -> CGFloat {
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpace
        paragraphStyle.lineBreakMode = .byWordWrapping;
        let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraphStyle.copy(), NSAttributedString.Key.kern: kernSpace]
        let text = textStr as NSString
        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil)
        return rect.size.height
    }
    /// 计算文字宽度
    func wn_getTexWidth(textStr: String, font: UIFont, height: CGFloat) -> CGFloat {
        let normalText: NSString = textStr as NSString
        let size = CGSize.init(width: 1000, height: height)
        let dic = NSDictionary(object: font, forKey: kCTFontAttributeName as! NSCopying)
        let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : AnyObject], context:nil).size
        return stringSize.width
    }
}

//MARK: - 吐司
extension UIViewController {
    /// MARK: - 吐司
    func wn_toast(_ text: String, _ delay: TimeInterval = 1.5) {
        WNHUD.wn_show(text, delay)
    }
    
    /// 底部弹出系统Alert
    func wn_showAlert(_ title: String?, _ message: String?, _ leftName: String?, _ rightName: String?, firstAction: @escaping ReturnClosure, secondAction: @escaping ReturnClosure) {
        let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
        if !isBlank(leftName) {
            let firstNameAction = UIAlertAction(title: leftName, style: .default) { (action) in
                firstAction()
            }
            alert.addAction(firstNameAction)
        }
        if !isBlank(rightName) {
            let secondNameAction = UIAlertAction(title: rightName, style: .default) { (action) in
                secondAction()
            }
            alert.addAction(secondNameAction)
        }
        self.present(alert, animated: true, completion: nil)
    }
    
    /// 底部弹出两个系统ActionSheet
    func wn_showActionSheet(_ title: String?, _ message: String?, _ firstName: String?, _ secondName: String?, _ cancelName: String = "取消", firstAction: @escaping ReturnClosure, secondAction: @escaping ReturnClosure) {
        let alert = UIAlertController.init(title: title, message: message, preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: cancelName, style: .cancel, handler: nil)
        if !isBlank(firstName) {
            let firstNameAction = UIAlertAction(title: firstName, style: .default) { (action) in
                firstAction()
            }
            alert.addAction(firstNameAction)
        }
        if !isBlank(secondName) {
            let secondNameAction = UIAlertAction(title: secondName, style: .default) { (action) in
                secondAction()
            }
            alert.addAction(secondNameAction)
        }
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }
}

//MARK: - VC统一处理
extension UIViewController {
    /// 跳转WebView
    func wn_pushWebVC(_ urlStr: String, _ titleStr: String, _ hideBar: Bool = true) {
        let webVC = WNBaseWebVC()
        webVC.urlStr = urlStr
        webVC.titleStr = titleStr
        webVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.pushViewController(webVC, animated: true)
    }
    
    /// 跳转book
    func wn_pushBookVC(_ bookId: String, _ chapterId: String = "", _ hideBar: Bool = true) {
        guard !isBlank(bookId) else { return }
        let controllers = navigationController?.viewControllers
        var newControllers = [UIViewController]()
        if let vcArr = controllers, vcArr.count > 0 {
            for item in vcArr {
                if item.isKind(of: WNReadVC.self) {
                    (item as? WNReadVC)?.stopReadTimer(true, false)
                }else {
                    newControllers.append(item)
                }
            }
        }
        let bookVC = WNBookVC()
        bookVC.baseId = bookId
        if chapterId != "0" || chapterId != "" {
            bookVC.jumpChapterId = chapterId
        }
        newControllers.append(bookVC)
        bookVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.setViewControllers(newControllers, animated: true)
    }
    
    /// 跳转阅读
    func wn_pushReadVC(_ boodModel: BookDetailModel?, _ chapterId: String = "", _ hideBar: Bool = true) {
        guard !isBlank(boodModel?.bookId) else { return }
        closeSuspendView()
        hidenTabLast()
        let readVC = WNReadVC()
        readVC.bookDetailModel = boodModel
        readVC.jumpChapterId = chapterId
        navigationController?.pushViewController(readVC, animated: true)
    }

    /// 跳转同类型
    func wn_pushTypeBookVC(_ model: TagsModel?, _ isTag: Bool = true, _ hideBar: Bool = true) {
        let typeVC = WNTypeBookVC()
        typeVC.tagModel = model
        typeVC.isTag = isTag
        typeVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.pushViewController(typeVC, animated: true)
    }

    /// 跳转Store
    func wn_pushStoreVC(_ hideBar: Bool = true) {
        let storeVC = WNStoreVC()
        storeVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.pushViewController(storeVC, animated: true)
    }
    
    /// 跳转Earn
    func wn_pushEarnVC(_ hideBar: Bool = true) {
        let earnVC = WNEarnVC()
        earnVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.pushViewController(earnVC, animated: true)
    }
    
    /// 跳转Task
    func wn_pushTaskVC(_ hideBar: Bool = true) {
        let taskVC = WNTaskVC()
        taskVC.hidesBottomBarWhenPushed = hideBar
        navigationController?.pushViewController(taskVC, animated: true)
    }
    
    /// 跳转音频
    func wn_pushAudioVC(_ audioModel: MusicModel?, _ musicId: String = "", _ hideBar: Bool = true) {
        guard !isBlank(audioModel?.bookId) else { return }
        closeSuspendView()
        hidenTabLast()
        let readVC = WNAudioVC()
        readVC.baseId = audioModel?.bookId ?? ""
        readVC.musicId = musicId
        navigationController?.pushViewController(readVC, animated: true)
    }

    /// 模态搜索
    func wn_presentSearchVC(_ hideBar: Bool = true) {
        let searchVC = WNSearchVC()
        let searchNav = WNBaseNaviVC(rootViewController: searchVC)
        searchNav.modalPresentationStyle = .overFullScreen
        present(searchNav, animated: true, completion: nil)
    }

    /// 模态登录
    func wn_presentLogin(_ hidBack: Bool = false) {
        let loginVC = WNLoginVC()
        let loginNav = WNBaseNaviVC(rootViewController: loginVC)
        loginNav.modalPresentationStyle = .overFullScreen
        present(loginNav, animated: true, completion: nil)
    }
    
    /// 更换root为Home
    func changeMainRoot() {
        let window = appDelegate.wn_window
        let vc = WNTabBarVC()
        vc.modalTransitionStyle = .crossDissolve
        let mianTabbarVC = WNBaseNaviVC(rootViewController: vc)
        UIView.transition(with: window!, duration: 0.25, options: UIView.AnimationOptions.transitionCrossDissolve, animations: {
            let oldState = UIView.areAnimationsEnabled
            UIView.setAnimationsEnabled(false)
            window?.rootViewController = mianTabbarVC
            window?.makeKeyAndVisible()
            UIView.setAnimationsEnabled(oldState)
        }) { finish in
            if finish {
                vc.handleConfig()
            }
        }
    }
}

extension UIPageViewController {
    var isPagingEnabled: Bool {
        get {
            return scrollView?.isScrollEnabled ?? false
        }
        set {
            scrollView?.isScrollEnabled = newValue
        }
    }

    var scrollView: UIScrollView? {
        return view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView
    }
}

//MARK: - 小窗口
extension WNReadVC {
    
    func wn_suspend(_ model: BookDetailModel?) {
        view.layer.masksToBounds = true
        UIView.animate(withDuration: 0.25, animations: {
            self.view.frame = CGRect.init(origin: WNSuspendTool.shared.origin, size: CGSize.init(width: 80, height: 80))
            self.view.layoutIfNeeded()
        }) { (complete) in
            self.navigationController?.popViewController(animated: false)
            WNSuspendTool.showSuspendWindow(0, self, model, nil)
        }
    }

    func wn_showFullView() {
        wn_getTopVC()?.navigationController?.pushViewController(self, animated: false)
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear], animations: {
            self.view.frame = UIScreen.main.bounds
        }) { (finish) in
            if finish {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    func wn_spread(from point: CGPoint) {
        if let isContain = self.navigationController?.viewControllers.contains(self), isContain {
            return
        }
        view.frame = CGRect.init(origin: point, size: CGSize.init(width: 80, height: 80))
        wn_getTopVC()?.navigationController?.pushViewController(self, animated: false)
        UIView.animate(withDuration: 0.25, animations: {
            self.view.layer.cornerRadius = 0
            self.view.frame = UIScreen.main.bounds
            self.view.layoutIfNeeded()
        })
    }
}


//MARK: - 小窗口
extension WNAudioVC {
    
    func wn_suspend(_ type: Int, _ audioModel: MusicModel?) {
        view.layer.masksToBounds = true
        UIView.animate(withDuration: 0.25, animations: {
            self.view.frame = CGRect.init(origin: WNSuspendTool.shared.origin, size: CGSize.init(width: 80, height: 80))
            self.view.layoutIfNeeded()
        }) { (complete) in
            self.navigationController?.popViewController(animated: false)
            WNSuspendTool.showSuspendWindow(1, self, nil, audioModel)
        }
    }

    func wn_showFullView() {
        wn_getTopVC()?.navigationController?.pushViewController(self, animated: false)
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear], animations: {
            self.view.frame = UIScreen.main.bounds
        }) { (finish) in
            if finish {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    func wn_spread(from point: CGPoint) {
        if let isContain = self.navigationController?.viewControllers.contains(self), isContain {
            return
        }
        view.frame = CGRect.init(origin: point, size: CGSize.init(width: 80, height: 80))
        wn_getTopVC()?.navigationController?.pushViewController(self, animated: false)
        UIView.animate(withDuration: 0.25, animations: {
            self.view.layer.cornerRadius = 0
            self.view.frame = UIScreen.main.bounds
            self.view.layoutIfNeeded()
        })
    }
}
